package com.mall.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * @Description List与Byte相互转换工具类
 * @ClassName ListByteConverterUtil
 * @Author cxx
 * @Date 2023/6/6 13:54
 * @Version 1.0
 */

public class ListByteConverterUtil {
    /**
     * list转换为Byte数组
     *
     * @param list
     * @return byte[]
     * @author cxx
     * @date 2023/6/6 13:55
     */
    public static byte[] listToByteArray(List<?> list) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(list);
        byte[] bytes = baos.toByteArray();
        oos.close();
        baos.close();
        return bytes;
    }

    /**
     * Byte数组转换为List
     *
     * @return java.util.List<?>
     * @author cxx
     * @date 2023/6/6 13:56
     * @param    bytes
     */
    public static List<?> byteArrayToList(byte[] bytes) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        List<?> list = (List<?>) ois.readObject();
        ois.close();
        bais.close();
        return list;
    }
}
